package com.atguigu.config;

import com.atguigu.entity.Admin;
import com.atguigu.service.AdminService;
import com.atguigu.service.PermissionService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Date:2022/11/9
 * Author:ybc
 * Description:
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @DubboReference
    private AdminService adminService;
    @DubboReference
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        Admin admin =  adminService.findAdminByUsername(username);
        //判断根据用户名是否查询到了用户信息
        if(admin == null){
            //表示未查询到用户信息
            return null;
        }
        //表示根据用户名查询到了用户信息，查询用户所对应的权限信息
        List<String> permissionCodeList = permissionService.findPermissionCodeListByAdminId(admin.getId());
        Set<GrantedAuthority> authorities = new HashSet<>();
        for (String permissionCode : permissionCodeList) {
            authorities.add(new SimpleGrantedAuthority(permissionCode));
        }
        return new User(username, admin.getPassword(), authorities);
    }

}
